package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.View;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.FUsers;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.ShortVideoAdapter;
import com.sctvcloud.dongqu.ui.adapter.SpecialFrgAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.VideoPlayHolder;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.GlideCircleTransform;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;
import com.sctvcloud.dongqu.ui.utils.UIUtils;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.sctvcloud.dongqu.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 威远---短视频列表-改
 */
public class ShortVideoActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ShortVideoAdapter.OnVideoClickListener {
    @BindView(R.id.common_frg_refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.no_data)
    protected CustomFontTextView noDataView;

    private List<NewsItem> newsList = new ArrayList<>();
    private ShortVideoAdapter mAdapter;
    private boolean isLoading = false;
    private String lastChannelId = "";
    private int currentPage = 0;
    private int pageAll = 0;
    private int lastLoadMoreIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("短视频");
        lastChannelId = Cache.getInstance().getCurrentChannelId();
        String channelID = Cache.getInstance().getCurrentColumnId("精选", "精选");
        Cache.getInstance().setCurrentChannelId(channelID);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_short_video);
        ButterKnife.bind(this);
    }

    private void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(0));
        mAdapter = new ShortVideoAdapter(this, this);
        mRecyclerView.setAdapter(mAdapter);

        mRefreshLayout.autoRefresh();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int topPosition = layoutManager.findFirstVisibleItemPosition();
                int bottomPosition = layoutManager.findLastVisibleItemPosition();
                if (dy > 0 && bottomPosition >= (newsList.size() - 3) && bottomPosition != lastLoadMoreIndex) {
                    //向上滑动到距离列表最后一项还有2条时，加载更多
                    lastLoadMoreIndex = bottomPosition;
                    loadMore(0);
                }
            }
        });
    }

    @Override
    public void onLoadMore() {
//        if (!isLoading) {
//            currentPage = currentPage + 1;
//            if (currentPage < pageAll) {
//                getHotVideoList(currentPage);
//            } else {
//                onNetFinish();
//                Toast.makeText(this, "没有更多视频了", Toast.LENGTH_LONG).show();
//            }
//        }
        mRefreshLayout.loadMoreComplete();
    }

    private void loadMore(int type) {
        if (!isLoading) {
            currentPage = currentPage + 1;
            if (currentPage < pageAll) {
//                loadMoreType = type;
//                Toast.makeText(this, "更多视频了", Toast.LENGTH_LONG).show();
                getHotVideoList(currentPage);
            } else {
                onNetFinish();
                if (type == 1) {
                    Toast.makeText(this, "没有更多视频了", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    public void onRefresh() {
        int currentPage = 0;
        getHotVideoList(currentPage);
    }


    /**
     * 请求短视频的数据
     */
    private void getHotVideoList(int calledPage) {
        isLoading = true;
        Map<String, Object> param = new ArrayMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("page", calledPage);
        param.put("size", 10);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        NetUtils.getNetAdapter().getShortVideos(getOwnerName(), param, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), calledPage) {

            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    pageAll = getPageResponse().getData().getPageAll();
                    currentPage = getPageResponse().getData().getPageIndex();
                    if (currentPage == 0) {
                        newsList.clear();
                        newsList.addAll(newsItems);
                        mAdapter.setData(newsItems);
                    } else {
                        newsList.addAll(newsItems);
                        mAdapter.setData(newsList);
                    }

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }

        });


    }


    private synchronized void onNetFinish() {
        isLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(currentPage >= pageAll ? false : true);
        if (currentPage == 0 && newsList.size() == 0) {
            mRefreshLayout.setVisibility(View.GONE);
            noDataView.setVisibility(View.VISIBLE);
        } else {
            mRefreshLayout.setVisibility(View.VISIBLE);
            noDataView.setVisibility(View.GONE);
        }
    }

    @Override
    public void OnVideoClick(int position) {
        if (ListUtils.isListValued(newsList)) {
            Cache.getInstance().setShortVideonList(newsList);
            Intent intent = new Intent(this, VideoPlayViewActivity.class);
            intent.putExtra(VideoPlayViewActivity.JUMP_INTO_INDEX, position);
            intent.putExtra(VideoPlayViewActivity.JUMP_INTO_PAGE_INDEX, currentPage);
            intent.putExtra(VideoPlayViewActivity.JUMP_INTO_PAGEALL_INDEX, pageAll);
            startActivity(intent);
        }
    }


    @Override
    protected void onDestroy() {
        Cache.getInstance().setCurrentChannelId(lastChannelId);
        super.onDestroy();
        mRecyclerView = null;
    }
}
